package com.dhecp.project.hr.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.core.utils.ReflectUtils;
import com.dhecp.project.common.domain.ModuleNID;
import com.dhecp.project.common.domain.RecordCheck;
import com.dhecp.project.common.domain.UpdateDeleted;
import com.dhecp.project.common.domain.UpdateFlow;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.flowable.domain.SysProcessInstance;
import com.dhecp.project.flowable.mapper.SysProcessInstanceMapper;
import com.dhecp.project.hr.domain.OperateCompanyApply;
import com.dhecp.project.hr.domain.OperateCompanyExit;
import com.dhecp.project.hr.mapper.OperateCompanyApplyMapper;
import com.dhecp.project.hr.service.OperateCompanyApplyService;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * 运营公司备案 服务层
 *
 * @author DH-Xxj
 * @version 2022年3月3日
 */
@Service
public class OperateCompanyApplyServiceImpl extends BaseModuleServiceImpl implements OperateCompanyApplyService {

    @Autowired
    private OperateCompanyApplyMapper businessMapper;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;
    @Autowired
    private SysProcessInstanceMapper sysProcessInstanceMapper;

    /**
     * 根据公司全称查找
     */
    @Override
    public OperateCompanyApply findByShortName(String shortName) {    //服务器名,用于区分当前服务器附件数
        return businessMapper.findByShortName(shortName);
    }

    /**
     * 根据公司编码查找
     */
    @Override
    public OperateCompanyApply findByGsbm(String gsbm) {    //服务器名,用于区分当前服务器附件数
        return businessMapper.findVGsBm(gsbm);
    }

    /**
     * 查询前一单NID、BID
     *
     * @param nid 必要参数：当前 单据编码
     * @return AjaxResult (data.nid 前一单NID， data.bid 前一单BID)
     * @throws Exception
     * @author DH-Xxj
     */
    @Override
    public AjaxResult queryLastNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == "") {
            params.put("nid", "0");
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        ModuleNID moduleNID = businessMapper.selectLastNid(params);
        if (moduleNID == null) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfirstnid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }

    /**
     * 查询后一单NID、BID
     *
     * @param nid 必要参数：当前 单据编码
     * @return AjaxResult (data.nid 后一单NID， data.bid 后一单BID)
     * @throws Exception
     * @author DH-Xxj
     */
    @Override
    public AjaxResult queryNextNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == "" || "0".equals(params.get("nid").toString())) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        ModuleNID moduleNID = businessMapper.selectNextNid(params);
        if (moduleNID == null) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }

    /**
     * 查询指定单nid的首记录
     *
     * @param params
     * @return OperateCompanyApply
     * @throws Exception
     * @author DH-Xxj
     */
    @Override
    public OperateCompanyApply queryFirstRecord(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return businessMapper.selectFirstRecordByNid(params);
    }

    /**
     * 查询指定单nid的整单录
     *
     * @param nid 必要参数：当前 单据编码
     * @return List - OperateCompanyApply
     * @throws Exception
     * @author DH-Xxj
     */
    @Override
    public List<OperateCompanyApply> queryListByNid(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return businessMapper.selectByNid(params);
    }

    /**
     * 查询
     *
     * @param params
     * @return List - OperateCompanyApply
     * @throws Exception
     * @author DH-Xxj
     */
    @Override
    public List<OperateCompanyApply> queryList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        PageUtils.startPageStronger();
        return businessMapper.select(params);
    }


    /**
     * 查询
     *
     * @param params
     * @return List - OperateCompanyApply
     * @throws Exception
     * @author fxz
     */
    @Override
    public List<OperateCompanyApply> queryList2(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        PageUtils.startPageStronger();
        return businessMapper.select2(params);
    }

    /**
     * 查询未流转完的数据
     *
     * @author XDH
     */
    @Override
    public List<OperateCompanyApply> queryListUnEnd() {
        return businessMapper.listUnEnd();
    }

    /**
     * 查询所有流转完成的
     */
    @Override
    public List<OperateCompanyApply> listAllOn() {
        return businessMapper.listAllOn();
    }

    /**
     * 查询未流转完的数据
     *
     * @author XDH
     */
    @Override
    public Map<String, Object> queryMapByGuid(String guid) {
        return businessMapper.queryMapByGuid(guid);
    }

    /**
     * 保存
     *
     * @param moduleTable 必要参数：功能唯一标识
     * @param infoMap     必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @param infoItems   必要参数：对应实体类的json格式字符串
     * @return AjaxResult
     * @author DH-Xxj
     */
    @SuppressWarnings("unchecked")
    @Override
    public AjaxResult saveData(Map<String, Object> params) {
        params.put("businessEntity", new OperateCompanyApply());

        AjaxResult ajaxResult = this.saveDataBase(params);
        if (!"0".equals(ajaxResult.get("code").toString())) {
            throw new RuntimeException(ajaxResult.get("msg").toString());
        }

        String resNid = "0";
        Map<String, Object> infoMap = (Map<String, Object>) ajaxResult.get("infoMap");
        List<OperateCompanyApply> businessDataList = (List<OperateCompanyApply>) ajaxResult.get("businessDataList");

        List<RecordCheck> guidMapList = businessMapper.findRecords(infoMap.get("nid").toString());
        Map<String, Object> guidMap = new HashMap<String, Object>();
        if (!guidMapList.isEmpty() && guidMapList.size() > 0) {
            if (infoMap.get("newNid") != null && "1".equals(infoMap.get("newNid").toString())) { //单号重复验证
                throw new RuntimeException(MessageUtils.message("module.error.retry"));
            }
            for (RecordCheck recordCheck : guidMapList) {
                if (recordCheck != null && recordCheck.getGuid() != null) {
                    guidMap.put(recordCheck.getGuid().toString(), "1");
                }
            }
        }

        if (businessDataList == null || businessDataList.size() == 0) {
            resNid = "0";
        } else {
            resNid = infoMap.get("nid").toString();
            for (OperateCompanyApply businessData : businessDataList) {
                String guid = "";
                if (businessData.getGuid() == null) {
                    guid = RandomValueUtils.getGUID();
                    businessData.setGuid(guid);
                } else {
                    guid = businessData.getGuid().toString();
                }

                for (String field : infoMap.keySet()) { //遍历非网格字段，并赋值到实体中
                    Object fieldValue = infoMap.get(field);
                    ReflectUtils.setValue(businessData, field, fieldValue);
                }
                
                // 验证税号是否存在
                OperateCompanyApply entityForCheck = businessMapper.findByVGsSh(businessData.getvGsSh());

                if (guidMap.get(guid) == null) {
                	if (entityForCheck != null && !entityForCheck.getvGsMc().equals(businessData.getvGsMc())) {
						return AjaxResult.error("该税号已存在");
					}
                    businessMapper.insert(businessData);
                } else {
                	if (entityForCheck != null && !entityForCheck.getvGsMc().equals(businessData.getvGsMc())) {
						return AjaxResult.error("该税号已存在");
					}
                    businessMapper.update(businessData);
                    guidMap.remove(guid);
                }
            }
        }

        if (!guidMap.isEmpty()) {
            for (String guid : guidMap.keySet()) {
                businessMapper.delete(guid);
            }
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), resNid);
    }

    /**
     * 培训费调整
     */
    @Override
    public AjaxResult editGledfJe(String guid, BigDecimal gledfJe,String depositAccount,String depositInformation) {
    	OperateCompanyApply businessData = businessMapper.findByGuid(guid);
    	businessData.setGledfJe(gledfJe);
    	if (depositAccount != ""){
            OperateCompanyApply byDepositAccount = businessMapper.findByDepositAccount(depositAccount, guid);
            if (byDepositAccount != null){
                return AjaxResult.error("存款账户已存在,请核实后在操作!");
            }
        }
    	businessData.setDepositAccount(depositAccount);
    	businessData.setDepositInformation(depositInformation);

        businessMapper.update(businessData);
        
        return AjaxResult.success("修改成功");
    }

    /**
     * 修改税号
     */
    @Override
    public AjaxResult editVGsSh(String guid, String vGsMc, String vGsSh) {
    	
    	OperateCompanyApply businessData = businessMapper.findByGuid(guid);
        
        // 验证同一个公司名称，税号必须一样
        OperateCompanyApply entityForCheck1 = businessMapper.findByVGsMcExceptGuid(vGsMc, guid);
    	if (entityForCheck1 != null) {
    		String vGsShForCheck = entityForCheck1.getvGsSh();
    		if (vGsShForCheck != null && vGsShForCheck.length() > 0 && !vGsShForCheck.equals(vGsSh)) {
    			return AjaxResult.error("税号与该公司已存在的税号不一致");
			}
		}
        
        // 验证税号是否存在
        OperateCompanyApply entityForCheck2 = businessMapper.findByVGsShExceptGuid(vGsSh, guid);
    	if (entityForCheck2 != null && !entityForCheck2.getvGsMc().equals(vGsMc)) {
			return AjaxResult.error("该税号已存在");
		}

    	businessData.setvGsMc(vGsMc);;
    	businessData.setvGsSh(vGsSh);

        businessMapper.update(businessData);
        
        return AjaxResult.success("修改成功");
    }

    /**
     * 删除
     *
     * @param params
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult deleteData(Map<String, Object> params) {
        List<OperateCompanyApply> businessDataList = JSON.parseArray(params.get("infoItems").toString(), OperateCompanyApply.class);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (OperateCompanyApply businessData : businessDataList) {
            businessMapper.delete(businessData);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

    /**
     * 修改删除标志（预留）
     *
     * @param infoItems 必要参数：对应实体类的json格式字符串（仅需 guid 和 deleted）
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateDeleted(Map<String, Object> params) {
        List<UpdateDeleted> updateDeletedList = JSON.parseArray(params.get("infoItems").toString(), UpdateDeleted.class);
        if (updateDeletedList == null || updateDeletedList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (UpdateDeleted updateDeleted : updateDeletedList) {
            businessMapper.updateDeleted(updateDeleted);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

    /**
     * 流转  —— 添加流程任务、修改流程状态及生效标志
     *
     * @param tableDataId 必要参数：单据编码（nid）
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateFlowGo(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") == "") {
            return AjaxResult.error(MessageUtils.message("module.error.lack", "单据编码【tableDataId】"));
        } else {
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<OperateCompanyApply> businessDataList = businessMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        } else {
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == "") {
            params.put("optType", "go");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (OperateCompanyApply businessData : businessDataList) {
            updateFlow.setGuid(businessData.getGuid().toString());
            businessMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

    /**
     * 流转通过
     */
    @Override
    public AjaxResult updateFlowGoPass(String bid) {
        OperateCompanyApply entity = businessMapper.findByBid(bid);
        if (entity == null) {
            return AjaxResult.error("单据不存在");
        } else if (entity.getEffectStock() != false) {
            return AjaxResult.error("单据无需流转");
        }

        entity.setEffectStock(true);
        entity.setActiveFlow("end");
        entity.setUpdateTime(new Date());
        businessMapper.updateFlowPass(entity);

        // 更新ProcessInstance
        SysProcessInstance sysProcessInstance = sysProcessInstanceMapper.findSysProcessInstanceByProcInstId(entity.getProcInstId());
        sysProcessInstance.setPrevTaskId(sysProcessInstance.getNextTaskId());
        sysProcessInstance.setPrevActId("FlowZd");
        sysProcessInstance.setNextActId("sid-38691DC4-F610-492F-8036-8295310EB1F6");
        sysProcessInstance.setNextActAlias("end");
        sysProcessInstance.setActComment("");
        sysProcessInstance.setActFuncKey("");
        sysProcessInstance.setActFormPage("");
        sysProcessInstance.setDataStatus(2);
        sysProcessInstance.setResultStatus(2);
        sysProcessInstance.setUpdateUser("09933");
        sysProcessInstance.setUpdateTime(new Date());
        sysProcessInstanceMapper.update(sysProcessInstance);

        return AjaxResult.success();
    }

    /**
     * 退回  —— 添加流程任务、修改流程状态及生效标志
     *
     * @param tableDataId 必要参数：单据编码（nid）
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateFlowBack(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") == "") {
            return AjaxResult.error(MessageUtils.message("module.error.lack", "单据编码【tableDataId】"));
        } else {
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<OperateCompanyApply> businessDataList = businessMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        } else {
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == "") {
            params.put("optType", "back");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (OperateCompanyApply businessData : businessDataList) {
            updateFlow.setGuid(businessData.getGuid().toString());
            businessMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

    /**
     * 运营公司信息查询
     *
     * @param otherWhere 可选参数：查询附加条件[1：普通员工只查自己绑定的，管理员查全部]
     * @return List - OperateCompanyApply
     * @throws Exception
     * @author DH-Xxj
     */
    @Override
    public List<OperateCompanyApply> queryOperateCompanyInfoList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put("moduleTable", ModuleTable.OPERATE_COMPANY_APPLY);
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        params.put("moduleTable", ModuleTable.OPERATE_COMPANY_INFO);
        /*
        if (params.get("isFiltration") == null || params.get("isFiltration") == "") {
            params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
            String otherWhereStr = "";
            if (params.get("otherWhere") == null || params.get("otherWhere") == "") {
                otherWhereStr = "";
            } else if ("1".equals(params.get("otherWhere").toString()) && ShiroUtils.getMandatorLevel() < 6) {
                otherWhereStr = "t1.CUser = '" + ShiroUtils.getMandatorId() + "'";
            }
            if (!"".equals(otherWhereStr)) {
                params.put("otherWhereStr", otherWhereStr);
            }
        }
        */
        if (params.get("field") == null || params.get("field") == "") {
            String orderBy = "nid asc";
            PageUtils.startPageOrder(orderBy);
        } else {
            PageUtils.startPage();
        }
        return businessMapper.findOperateCompanyInfo(params);
    }

    /**
     * 从运营公司信息调入运营公司退出
     *
     * @param params
     * @return List - OperateCompanyExit
     * @throws Exception
     * @author DH-Xxj
     */
    @Override
    public List<OperateCompanyExit> callOperateCompanyExitList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        PageUtils.startPageStronger();
        return businessMapper.callOperateCompanyExit(params);
    }

}
